<template>
  <div class="container" ref="mainCon">
    <topTitle
      :titleText="titleText"
      :back="true"
      @gobackTriser="goBack"
    ></topTitle>
    <div class="mainCon">
      <el-form
        :model="formData"
        :rules="rules"
        ref="ruleForm"
        label-width="140px"
      >
        <div class="formBoxs">
          <div class="secondaryTitle secondaryTitleTheme">判断规则</div>
          <div class="secondaryTitleTips">
            符合以下规则的项目，建档时将被划分为小项目
          </div>
          <el-form-item label="区域：" prop="areaId">
            <el-cascader
              ref="manageArea"
              class="lWidth"
              :disabled="disabled || types == 'edit'"
              v-model="areaId"
              :options="areasOptionsData"
              @change="getAreaId"
              :props="{ checkStrictly: true }"
              clearable
              filterable
            ></el-cascader>
          </el-form-item>
          <el-form-item label="行业：" prop="industryId">
            <el-select
              class="lWidth"
              v-model="formData.industryId"
              multiple
              :disabled="disabled || types == 'edit'"
              filterable
              placeholder="请选择行业"
              clearable
            >
              <el-option
                v-for="item in industryOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工程造价：" prop="total">
            <p style="color: #606266">
              工程造价小于
              <el-input
                :disabled="disabled"
                class="sWidth"
                v-model="formData.total"
              ></el-input>
              元时，归档为小项目
            </p>
          </el-form-item>
          <el-form-item label="建设周期：" prop="cycle">
            <p style="color: #606266">
              建设周期小于
              <el-input
                :disabled="disabled"
                class="sWidth"
                v-model="formData.cycle"
              ></el-input>
              天时，归档为小项目
            </p>
          </el-form-item>
          <el-form-item label="历史项目归档：" prop="isArchive">
            <el-radio-group v-model="formData.isArchive" :disabled="disabled">
              <el-radio :label="0">不归档：已建档的普通项目不变更</el-radio>
              <el-radio :label="1">归档：所有项目按新规则归档</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <div class="formBoxs">
          <div class="secondaryTitle secondaryTitleTheme">小项目功能设置</div>
          <div class="secondaryTitleTips">
            附件备案等同于有实名制、考勤、工资代发；系统不对小项目评分
          </div>
          <el-form-item label="工人名册：" prop="isRegister">
            <el-radio-group
              v-model="formData.isRegister"
              :disabled="disabled"
              @change="handleReg"
            >
              <el-radio :label="1">录入实名制信息</el-radio>
              <el-radio :label="0">附件备案人员名单</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="工人考勤：" prop="isAtt">
            <el-radio-group
              v-model="formData.isAtt"
              :disabled="disabled"
              @change="handleAtt"
            >
              <el-radio :label="1">实名制打卡</el-radio>
              <el-radio :label="0">附件备案人员考勤信息</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="工资发放：" prop="isSalary">
            <el-radio-group
              v-model="formData.isSalary"
              class="salaryRadio"
              :disabled="disabled"
              @change="handleSalary"
            >
              <el-radio :label="1"
                >银行代发：使用银行代发功能发放工资，需开设工资专户，缴纳保证金</el-radio
              >
              <el-radio :label="0"
                >附件备案：备案工资发放记录，无需开设工资专户，缴纳保证金</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="工伤保险：" prop="isIns">
            <el-radio-group
              v-model="formData.isIns"
              :disabled="disabled"
              @change="handleIns"
            >
              <el-radio :label="1">缴纳工伤保险</el-radio>
              <el-radio :label="0">无需缴纳工伤保险</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否对项目预警：" prop="isAlert">
            <el-radio-group
              v-model="formData.isAlert"
              :disabled="disabled"
              @change="handleAlert"
            >
              <el-radio :label="0">否：不新增预警</el-radio>
              <!-- <el-radio :label="1" >是：按预警配置规则，预警项目问题</el-radio> -->
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否统计：" prop="isStats">
            <el-radio-group v-model="formData.isStats" :disabled="disabled">
              <el-radio :label="0">否</el-radio>
              <!-- <el-radio :label="1" >是</el-radio> -->
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否对项目评分：" prop="isCreait">
            <el-radio-group v-model="formData.isCreait" :disabled="disabled">
              <el-radio :label="0">否：默认不对小项目新增评价</el-radio>
              <!-- <el-radio :label="1">是：默认对小项目新增评价</el-radio> -->
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注：" prop="reason">
            <el-input
              type="textarea"
              :disabled="disabled"
              placeholder="请输入备注信息"
              v-model="formData.reason"
              :rows="5"
            ></el-input>
          </el-form-item>
          <el-form-item label="" style="margin-top: 40px" v-if="!disabled">
            <el-button
              class="commonBut saveBtn"
              type="primary"
              @click="toSave"
              :loading="isSaveLoading"
              >保存</el-button
            >
            <el-button class="commonBut" @click="goBack">取消</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <el-dialog
      title="提示"
      width="640px"
      :visible.sync="showDia"
      :close-on-click-modal="false"
      @close="handleClose"
      :modal-append-to-body="false"
    >
      <div class="dia-content">
        {{ tipsMsg }}
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="handleClose" class="cancel">取消</el-button>
        <el-button
          type="primary"
          @click.native="sureSave"
          class="save"
          :loading="isDelLoading"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapState, mapActions } from 'vuex'
export default {
  name: 'addSmallProjectRule',
  data() {
    var checkTotal = (rule, value, callback) => {
      var reg = /^(([1-9]\d*)(\.\d{1,2})?|0\.([1-9]|\d[1-9])|0)$/
      if (!reg.test(value)) {
        return callback(new Error('请输入整数或两位小数'))
      } else if (value <= 0) {
        return callback(new Error('工程造价应大于0'))
      } else {
        return callback()
      }
    }
    return {
      types: '',
      id: '',
      titleText: '新增小项目管理规则',
      disabled: false,
      areaId: '',
      formData: {
        areaId: '',
        industryId: [],
        total: '',
        cycle: '',
        isArchive: 0,
        isRegister: 1,
        isAtt: 1,
        isSalary: 1,
        isIns: 1,
        isAlert: 0,
        isStats: 0,
        isCreait: 0,
        reason: '',
      },
      rules: {
        areaId: [{ required: true, message: '请选择区域', trigger: 'change' }],
        industryId: [
          { required: true, message: '请选择行业', trigger: 'change' },
        ],
        total: [{ required: true, validator: checkTotal, trigger: 'blur' }],
        cycle: [
          { required: true, message: '请输入工程周期', trigger: 'blur' },
          {
            required: true,
            pattern: /(^[1-9]\d*$)/,
            message: '请输入大于等于0的整数',
            trigger: 'blur',
          },
        ],
        isArchive: [
          {
            required: true,
            message: '请选择历史项目是否归档',
            trigger: 'change',
          },
        ],
        isRegister: [
          {
            required: true,
            message: '请选择是否使用实名制管理',
            trigger: 'change',
          },
        ],
        isAtt: [
          {
            required: true,
            message: '请选择是否使用考勤管理',
            trigger: 'change',
          },
        ],
        isSalary: [
          {
            required: true,
            message: '请选择是否使用工资代发',
            trigger: 'change',
          },
        ],
        isIns: [
          {
            required: true,
            message: '请选择是否缴纳工伤保险',
            trigger: 'change',
          },
        ],
        isAlert: [
          {
            required: true,
            message: '请选择是否使用项目预警',
            trigger: 'change',
          },
        ],
        isCreait: [
          {
            required: true,
            message: '请选择对项目进行评分',
            trigger: 'change',
          },
        ],
        isStats: [
          {
            required: true,
            message: '请选择对项目进行统计',
            trigger: 'change',
          },
        ],
        reason: [{ max: 200, message: '最多可输入200字', trigger: 'blur' }],
      },
      isSaveLoading: false,
      tipsMsg: '',
      showDia: false,
      isDelLoading: false,
      areaOptionsData: [],
    }
  },
  mounted() {
    // this.getAreas({ areaId: this.$store.state.areaInfoArr.areaId})
    // this.getIndustry()
    const { types, id, assocId } = this.$route.query
    this.types = types
    this.id = id ? id : ''
    this.assocId = assocId ? assocId : ''
    this.disabled = types == 'look' ? true : false
    this.titleText =
      types == 'add'
        ? '新增小项目管理规则'
        : types == 'edit'
        ? '编辑'
        : '查看小项目管理规则'
    if (this.id) {
      this.getDetails(this.id)
    }
  },
  computed: {
    ...mapState(['industryOptions', 'areasOptions']),
    areasOptionsData() {
      const computedData = (arr) =>
        arr.forEach((v) =>
          v.value.length >= 6
            ? delete v.children
            : v.children && computedData(v.children)
        )
      computedData(this.areasOptions)
      return this.areasOptions
    },
  },
  methods: {
    ...mapActions(['getIndustry', 'getAreas']),
    // 返回
    goBack() {
      this.$router.push({
        path: '/home/smallProjectManage/smallProjectSet',
        name: 'smallProjectSet',
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/smallProjectManage/smallProjectSet',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    //获取小项目详情
    getDetails(id) {
      this.axios
        .post('api-p/smallprojectrule/getMiniDetail', { id })
        .then((res) => {
          if (!res.data.hasError) {
            const {
              projectId,
              areaId,
              industryId,
              total,
              cycle,
              isArchive,
              reason,
              isRegister,
              isAtt,
              isSalary,
              isIns,
              isAlert,
              isStats,
              isCreait,
            } = res.data.result
            this.formData = {
              areaId,
              industryId: [industryId],
              total,
              cycle,
              isArchive,
              reason,
              isRegister,
              isAtt,
              isSalary,
              isIns,
              isAlert,
              isStats,
              isCreait,
            }
            this.areaId = areaId
          } else {
            this.$message.error(response.data.errorMsg)
          }
        })
    },
    //选择区域
    getAreaId() {
      var areaId = this.areaId[this.areaId.length - 1]
      this.formData.areaId = areaId
    },
    //工人名册
    handleReg(value) {
      if (value === 0) {
        this.formData.isAtt = 0
        this.formData.isIns = 0
        this.formData.isSalary = 0
        this.formData.isAlert = 0
      }
    },
    //选择工人考勤
    handleAtt(value) {
      if (this.formData.isRegister === 0 && value === 1) {
        this.$message.warning('【工人名称】需选择：录入实名制信息')
        this.formData.isAtt = 0
        this.formData.isSalary = 0
        this.formData.isAlert = 0
      } else if (value === 0) {
        this.formData.isSalary = 0
        this.formData.isAlert = 0
      }
    },
    //工资发放
    handleSalary(value) {
      if (this.formData.isAtt === 0 && value === 1) {
        this.$message.warning('【工人考勤】需选择：实名制打卡')
        this.formData.isSalary = 0
      }
    },
    //
    handleIns(value) {
      if (this.formData.isRegister === 0 && value === 1) {
        this.$message.warning('【工人名称】需选择：录入实名制信息')
        this.formData.isIns = 0
      }
    },
    //预警
    handleAlert(value) {
      if (
        (this.formData.isSalary === 0 || this.formData.isIns === 0) &&
        value === 1
      ) {
        this.$message.warning(
          '【工资发放】需选择：银行代发；【工伤保险】需选择：缴纳工伤保险'
        )
        this.formData.isAlert = 0
      }
    },
    toSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.showDia = true
          if (this.formData.isArchive === 1) {
            this.tipsMsg =
              '根据新增规则，符合判断规则的历史项目和新建档项目，将归档为小项目；且小项目今后重新归档普通项目后，将不参与预警及信用评价，是否确认保存？'
          } else {
            this.tipsMsg =
              '符合判断规则的新建档项目，将归档为小项目；且小项目今后重新归档普通项目后，将不参与预警及信用评价，是否确认保存？'
          }
          if (this.id) {
            this.tipsMsg =
              '由于判断规则修改,当前规则下的所有项目将重新归档，是否确认修改？'
          }
        }
      })
    },
    sureSave() {
      this.isDelLoading = true
      let params = { ...this.formData }
      params.industryId = params.industryId.join(',')
      // console.log(params);

      if (this.id) {
        params.id = this.id
        params.assocId = this.assocId
        // this.$confirm(tipsMsg, "提示", {
        //     confirmButtonText: "确定",
        //     cancelButtonText: "取消",
        //     type: "warning"
        // })
        // .then(() => {
        //     this.axios.post( this.id? 'api-p/smallprojectrule/editSmallRule' : 'api-p/smallprojectrule/addSmallRule'
        //         ,params
        //     ).then(res=>{
        //         this.isDelLoading = false
        //         if(!res.data.hasError){
        //             this.$message.success(this.id ? '修改成功' : '添加成功');
        //             this.showDia = false
        //             this.goBack()
        //         }else{
        //             this.$message.error(res.data.errorMsg);
        //         }
        //     })
        // })
        // .catch(() => {
        //     this.isDelLoading = false
        // });
      }
      // else{
      this.axios
        .post(
          this.id
            ? 'api-p/smallprojectrule/editSmallRule'
            : 'api-p/smallprojectrule/addSmallRule',
          params
        )
        .then((res) => {
          this.isDelLoading = false
          if (!res.data.hasError) {
            this.showDia = false
            this.$message.success(this.id ? '修改成功' : '添加成功')
            this.goBack()
          } else {
            this.$message.error(res.data.errorMsg)
          }
        })
      // }
    },
    handleClose() {
      this.showDia = false
    },
  },
}
</script>
<style lang="less" scoped>
.mainCon {
  padding: 0 0 18px;
  .formBoxs {
    padding: 20px 80px 0.1px 24px;
    position: relative;
    &:first-child::after {
      width: 100%;
      position: absolute;
      content: '';
      height: 1px;
      left: 0;
      bottom: 0px;
      transform: scaleY(0.5);
      background-color: #e3e7e9;
    }
    /deep/.el-radio {
      width: 280px;
    }
    .salaryRadio {
      /deep/.el-radio {
        white-space: initial;
        width: 460px;
        display: block;
        line-height: 36px;
      }
    }
  }
  .secondaryTitleTips {
    margin-top: 10px;
    line-height: 14px;
    padding-bottom: 22px;
    font-size: 14px;
    color: #999;
    padding-left: 16px;
  }
}
</style>
